package com.itrip.repository.impl;

import com.itrip.document.Hotel;
import com.itrip.repository.HotelRepository;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Repository
public class HotelRepositoryImpl implements HotelRepository {

    private SolrClient solrClient=new HttpSolrClient.Builder("http://127.0.0.1:8983/solr").build();
    private SolrQuery solrQuery=new SolrQuery();

    @Override
    public List<Hotel> getHotel(String keyWord, int i, Integer pageSize) throws IOException, SolrServerException {
        if(keyWord!=""&&keyWord!=null){
            solrQuery.set("q","hotelName:"+keyWord+"");
        }else {
            solrQuery.set("q","*:*");
        }
        solrQuery.set("start",""+i+"");
        solrQuery.set("rows",""+pageSize+"");
        
        //开启高亮查询
        solrQuery.setHighlight(true);
        //添加高亮字段
        solrQuery.addHighlightField("hotelName");
        //添加前缀
        solrQuery.setHighlightSimplePre("<font color='blue'>");
        //添加后缀
        solrQuery.setHighlightSimplePost("</font>");
        //获取旅馆
        QueryResponse queryResponse = solrClient.query("hotel", solrQuery);
        List<Hotel> beans = queryResponse.getBeans(Hotel.class);
        //获取高亮自己
        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();


        //替换高亮字段
        for (int j = 0; j <beans.size(); j++) {
            String id = beans.get(j).getId();
            //获取当前对象高亮字节
            if(highlighting.get(id).get("hotelName")!=null){
                String hl=highlighting.get(id).get("hotelName").get(0);
                beans.get(j).setHotelName(hl);
            }
        }
        return beans;
    }

    @Override
    public int getHotelNum(String keyWord) throws IOException, SolrServerException {
        solrQuery.set("q","hotelName:"+keyWord+"");
        QueryResponse queryResponse = solrClient.query("hotel", solrQuery);
        return (int)queryResponse.getResults().getNumFound();
    }
}
